package leetcode.editor.cn.q0xx

import leetcode.editor.cn.ListNode

class Q02_Medium_addTwoNumbers {
    fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? {
        var head: ListNode? = null
        var tail: ListNode? = null
        var carry = 0
        var cur1 = l1
        var cur2 = l2
        while (cur1 != null || cur2 != null) {
            val n1 = cur1?.`val`?:0
            val n2 = cur2?.`val`?:0
            val sum = n1+n2+carry
            if (head == null) {
                head = ListNode(sum%10)
                tail = head
            } else {
                tail!!.next = ListNode(sum%10)
                tail = tail.next
            }
            carry = sum/10
            cur1 = cur1?.next
            cur2 = cur2?.next
        }
        if (carry > 0) {
            tail!!.next = ListNode(carry)
        }
        return head
    }
}